package com.bobo.serviceorder.lock;

import com.bobo.serviceorder.entry.TblOrderLock;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author bobo
 * @date 2021-04-13
 */
@Service
@Data
public class RedisLock implements Lock {

    @Autowired
    private RedisTemplate<Integer,Integer> redisTemplate;

    private ThreadLocal<TblOrderLock> tblOrderLockThreadLocal;

    @Override
    public void lock() {
        // 1、尝试加锁
        if(tryLock()) {
            return;
        }
        // 2.休眠
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 3.递归再次调用
        lock();
    }

    @Override
    public boolean tryLock() {
        TblOrderLock tblOrderLock = tblOrderLockThreadLocal.get();
        int orderId = tblOrderLock.getOrderId();
        int driverId = tblOrderLock.getDriverId();

        return redisTemplate.opsForValue().setIfAbsent(orderId, driverId, 50, TimeUnit.SECONDS);
    }

    @Override
    public void unlock() {
        TblOrderLock tblOrderLock = tblOrderLockThreadLocal.get();
        DefaultRedisScript<List> getRedisScript = new DefaultRedisScript<List>();
        getRedisScript.setResultType(List.class);
        getRedisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("luascript/lock.lua")));

        redisTemplate.execute(getRedisScript, Arrays.asList(tblOrderLock.getOrderId()), Arrays.asList(tblOrderLock.getDriverId()));
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }



    @Override
    public Condition newCondition() {
        return null;
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }
}
